import MOCK_IMAG from './mock/imgs.json'
import MOCK_NAME from './mock/name.json'

export interface ImageType {
  src: string
  id: string
}

/** 上传图片 */
export async function upload(files: FileList | null): Promise<ImageType[]> {
  console.log(files)

  const count = files?.length || 0
  if (count === 0) return []

  function getCountImg(left: number): string[] {
    if (left <= MOCK_IMAG.length) {
      return MOCK_IMAG.slice(0, count)
    } else {
      return [...MOCK_IMAG, ...getCountImg(left - MOCK_IMAG.length)]
    }
  }

  const images: string[] = getCountImg(count)

  console.log(images)

  return Promise.resolve(
    images.map((src) => {
      return {
        src,
        id: uuid(), // 由于用户可以继续上传，所以需要添加一个唯一标识用于状态变更
      }
    })
  )
}

export interface IdentifyResItem {
  name?: string
  error?: boolean
  errorMessage?: string
  id: string
}

/** 识别图片 */
export async function identify(
  params: ImageType[]
): Promise<IdentifyResItem[]> {
  await randomDelay()

  return Promise.resolve(
    params.map((v) => {
      return {
        id: v.id,
        error: randomBoolean(),
        errorMessage: '图片识别错误',
        name: MOCK_NAME[randomNumber(0, MOCK_NAME.length - 1)],
      }
    })
  )
}

/** 保存数据 */
export async function save(ids: string[]): Promise<void> {
  console.log('保存操作', ids)

  await randomDelay()

  return Promise.resolve()
}

/** 随机延迟，用于模拟网络请求 */
async function randomDelay(): Promise<void> {
  const t = randomNumber(300, 1500)

  return new Promise((resolve) => {
    setTimeout(() => {
      resolve()
    }, t)
  })
}

/** 生成范围随机数 */
function randomNumber(min?: number, max?: number) {
  switch (arguments.length) {
    case 1:
      return parseInt(String(Math.random() * min! + 1), 10)
    case 2:
      return parseInt(String(Math.random() * (max! - min! + 1) + min!), 10)
    default:
      return 0
  }
}

/** 生成布尔值，1/3概率为 true */
function randomBoolean(): boolean {
  return randomNumber(0, 2) === 0
}

/** 生成一组随机 ID */
export function uuid(t = 'id-xxxxxxx'): string {
  return t.replace(/[xy]/g, function (c) {
    const r = (Math.random() * 16) | 0,
      v = c == 'x' ? r : (r & 0x3) | 0x8
    return v.toString(16)
  })
}
